package dhy.com.tomcat.four.core.stream;

import dhy.com.tomcat.four.header.HttpHeader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * <P>
 *     自定义的socket通信流
 * </P>
 */
public class SocketInputStream extends InputStream {
    private BufferedReader reader;
    public SocketInputStream(InputStream inputStream) {
      reader=new BufferedReader(new InputStreamReader(inputStream));
    }

    @Override
    public int read() throws IOException {
        return 0;
    }

    /**
     * 解析请求头
     */
    public void readHeader(HttpHeader header) {
        try {
            String h= reader.readLine();
            //请求头解析完毕
            if(h==null||h.equals("\r\n")||h.equals(""))
            {
                header=null;
                return;
            }
            String[] split = h.split(": ");
            String key = split[0];
            String value = split[1];
            header.setKey(key);
            header.setValue(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析请求第一行
     */
    public void readRequestLine(HttpRequestLine requestLine) {
        try {
            String line = reader.readLine();
            String[] params = line.split(" ");
            requestLine.method=params[0];
            requestLine.uri=params[1];
            requestLine.protocol=params[2];
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
